package com.parking.carsystem.parkingchargesystem.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.Headers;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.activity.AuthenticationActivity;
import com.parking.carsystem.parkingchargesystem.activity.ChooseLisencePlateActivity;
import com.parking.carsystem.parkingchargesystem.activity.CouponActivity;
import com.parking.carsystem.parkingchargesystem.activity.InvoiceMessageActivity;
import com.parking.carsystem.parkingchargesystem.activity.LoginActivity;
import com.parking.carsystem.parkingchargesystem.activity.MainActivity;
import com.parking.carsystem.parkingchargesystem.activity.MonthlySubscriptionActivity;
import com.parking.carsystem.parkingchargesystem.activity.PaySettingActivity;
import com.parking.carsystem.parkingchargesystem.activity.RechargeMoneyActivity;
import com.parking.carsystem.parkingchargesystem.activity.UserRechargeActivity;
import com.parking.carsystem.parkingchargesystem.common.CarApp;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.HomeImageModule;
import com.parking.carsystem.parkingchargesystem.module.UserInfoModel;
import com.parking.carsystem.parkingchargesystem.view.PorterShapeImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import ttyy.com.recyclerexts.base.EXTRecyclerAdapter;
import ttyy.com.recyclerexts.base.EXTViewHolder;

public class UserFragment extends Fragment implements View.OnClickListener {
    Unbinder unbinder;
    @BindView(R.id.use_image)
    PorterShapeImageView useImage;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.safe_image)
    ImageView safeImage;
    @BindView(R.id.list_message)
    RecyclerView listMessage;
    @BindView(R.id.user_function)
    RecyclerView userFunction;
    @BindView(R.id.login_out)
    TextView loginOut;
    @BindView(R.id.authentication)
    TextView authentication;
    @BindView(R.id.layout_authentication)
    LinearLayout layoutAuthentication;
    private EXTRecyclerAdapter<HomeImageModule> recyclerAdapter;
    private ArrayList<HomeImageModule> imageModules;
    ArrayList<String> listfunctions;
    private EXTRecyclerAdapter<String> listFunctionsAdapter;
    private MainActivity mActivity;
    private UserInfoModel userMessage;
    private GlideUrl glideUrl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_usercenter, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        initView();
        return inflate;
    }

    private void initView() {
        mActivity = (MainActivity) getActivity();
        loginOut.setOnClickListener(this);
        useImage.setOnClickListener(this);
        if (imageModules == null) {
            imageModules = new ArrayList<>();
            HomeImageModule homeImageModule = new HomeImageModule();
            homeImageModule.imageId = R.mipmap.icon_user_car;
            homeImageModule.name = "车辆管理";
            imageModules.add(homeImageModule);
            HomeImageModule homeImageModule1 = new HomeImageModule();
            homeImageModule1.imageId = R.mipmap.icon_user_coupon;
            homeImageModule1.name = "优惠卷";
            imageModules.add(homeImageModule1);
            HomeImageModule homeImageModule2 = new HomeImageModule();
            homeImageModule2.imageId = R.mipmap.icon_user_month;
            homeImageModule2.name = "我的月卡";
            imageModules.add(homeImageModule2);
            HomeImageModule homeImageModule3 = new HomeImageModule();
            homeImageModule3.imageId = R.mipmap.icon_user_money;
            homeImageModule3.name = "用户充值";
            imageModules.add(homeImageModule3);
        }
        listMessage.setLayoutManager(new GridLayoutManager(mActivity, 4));
        recyclerAdapter = new EXTRecyclerAdapter<HomeImageModule>(R.layout.item_user_image) {
            @Override
            public void onBindViewHolder(EXTViewHolder extViewHolder, int i, HomeImageModule module) {
                HomeImageModule homeImageModule = imageModules.get(i);
                extViewHolder.setImageResouce(R.id.image, homeImageModule.imageId);
                extViewHolder.setText(R.id.name, homeImageModule.name);
            }
        };
        recyclerAdapter.setDatas(imageModules);
        listMessage.setAdapter(recyclerAdapter);
        recyclerAdapter.setOnItemClickListener(new EXTRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(View view, int i) {
                Intent intent = null;
                //点击事件
                if (i == 1) {
                    //优惠券页面
                    if (CarApp.rowsBean != null) {
                        intent = new Intent(mActivity, CouponActivity.class);
                        intent.putExtra(Constant.PLATENUMBER, CarApp.rowsBean.plateNumber);
                        startActivity(intent);
                    }
//                    intent = new Intent(UserCenterActivity.this, MapActivity.class);
//                    startActivity(intent);
                } else if (i == 0) {
                    intent = new Intent(mActivity, ChooseLisencePlateActivity.class);
                    startActivityForResult(intent, 0);
                } else if (i == 2) {
                    intent = new Intent(mActivity, MonthlySubscriptionActivity.class);
                    startActivity(intent);
                } else if (i == 3) {
                    intent = new Intent(mActivity, RechargeMoneyActivity.class);
                    startActivity(intent);
                }
            }
        });
        if (listfunctions == null) {
            listfunctions = new ArrayList<>();
        }
        listfunctions.clear();
        listfunctions.add(getResources().getString(R.string.my_wallet));
        listfunctions.add(getResources().getString(R.string.real_name_authentication));
        listfunctions.add(getResources().getString(R.string.invoice_information));
        listfunctions.add(getResources().getString(R.string.privacy_free_login));
        listfunctions.add(getResources().getString(R.string.help_center));
        listfunctions.add(getResources().getString(R.string.contact_customer_service));
        listfunctions.add(getResources().getString(R.string.about_us));
        userFunction.setLayoutManager(new LinearLayoutManager(mActivity));
        listFunctionsAdapter = new EXTRecyclerAdapter<String>(R.layout.item_list_function) {
            @Override
            public void onBindViewHolder(EXTViewHolder extViewHolder, int i, String s) {
                extViewHolder.setText(R.id.text, s);
            }
        };
        listFunctionsAdapter.setDatas(listfunctions);
        userFunction.setAdapter(listFunctionsAdapter);
        listFunctionsAdapter.setOnItemClickListener(new EXTRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(View view, int i) {
                Intent intent = null;
                if (i == 2) {
                    //开票信息
                    intent = new Intent(mActivity, InvoiceMessageActivity.class);
                    startActivity(intent);
                } else if (i == 3) {
                    intent = new Intent(mActivity, PaySettingActivity.class);
                    startActivity(intent);
                } else if (i == 1) {
                    //实名认证
                    intent = new Intent(mActivity, AuthenticationActivity.class);
                    startActivity(intent);
                } else if (i == 0) {
                    intent = new Intent(mActivity, UserRechargeActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_out:
                Intent intent = new Intent(mActivity, LoginActivity.class);
                startActivity(intent);
                mActivity.finish();
                break;
            case R.id.use_image:
                mActivity.showChooseIdCardUploadPicWayDialog(Constant.REQUEST_CODE_OPEN_CAMERA, Constant.REQ_CODE_GALLERY_FACE);
                break;
        }
    }

    public void updateView() {
        userMessage = mActivity.getUserMessage();
        phone.setText(userMessage.data.phone);
        //显示图片的界面
        if (!TextUtils.isEmpty(userMessage.data.avatar)) {
            getHeader(userMessage.data.avatar);
        }
        Glide.with(getContext()).load(glideUrl).error(R.mipmap.user).into(useImage);
        if (TextUtils.isEmpty(userMessage.data.realName) || TextUtils.isEmpty(userMessage.data.idCardNo)) {
            authentication.setText("未认证");
            layoutAuthentication.setVisibility(View.INVISIBLE);
        } else {
            authentication.setText("已认证");
            layoutAuthentication.setVisibility(View.VISIBLE);
        }
    }

    private void getHeader(String avatar) {
        glideUrl = new GlideUrl(avatar, new Headers() {
            @Override
            public Map<String, String> getHeaders() {
                HttpHeaders commonHeaders = CarApp.okGo.getCommonHeaders();
                Map<String, String> header = new HashMap<>();
                //不一定都要添加，具体看原站的请求信息
                header.put("Authorization", commonHeaders.get("Authorization"));
                return header;
            }
        });
    }

    public void getPhotoFile(String takePhotoPath) {
        mActivity.showLoading();
        File file = new File(takePhotoPath);
        OkGo.<String>post(Constant.url + Constant.COMMONUPLOAD + "avatar")
                .params("file",file)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject1 = new JSONObject(response.body());
                            int code = jsonObject1.getInt("code");
                            String msg = jsonObject1.getString("msg");
                            String data = jsonObject1.getString("data");
                            if (code == 200) {
                                //显示图片的界面
                                getHeader(data);
                                Glide.with(getContext()).load(glideUrl).error(R.mipmap.user).into(useImage);
                                editUser(data);
                            } else {
                                mActivity.stopLoading();
                                mActivity.showToast(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        mActivity.stopLoading();
                    }
                });
    }

    private void editUser(String data) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("avatar",data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.<String>post(Constant.url+Constant.USEREDIT)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        mActivity.stopLoading();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        mActivity.stopLoading();
                    }
                });
    }
}
